//
//  MainView.swift
//  noteswift
//
//  Created by lzh on 2022/5/31.
//

import SwiftUI

struct MainView: View {
    @State var searchContent:String=""
    @State var isShowEdit=false
    @State var isShowOrderBy=false
    @ObservedObject var sqliteViewModel = NoteDBUtils.single
    @State var orderbyIndex:Int=0
    @State var orderbyStr:String="按创建日期排序"
    @State var isListModel:Bool=true
    private var gridItemLayout = [GridItem.init(.flexible(), spacing: 0, alignment: .center),                     GridItem.init(.flexible(), spacing: 0, alignment: .center),
                                  GridItem.init(.flexible(), spacing: 0, alignment: .center)]
    var width: CGFloat = UIScreen.main.bounds.width
    @State var isShowActionSheet=false
    @State private var navigationLinkActive = false
    
    init() {
        UITableViewCell.appearance().backgroundColor = UIColor.clear
    }
    var body: some View {
        let binding = Binding<String>(get: {
            self.searchContent
        }, set: {
            self.searchContent = $0
            sqliteViewModel.getNotes(keyWord: searchContent, orderby: orderbyIndex)
        })
        NavigationView{
            VStack{
                //                Text("备忘录")
                //                Divider()
                ZStack{
                    HStack{
                        Image("search")
                        
                        TextField("输入需要搜索的内容", text:binding).font(.subheadline)
                        Spacer()
                    }.padding(.leading,10).frame(height:40).cornerRadius(20).overlay(
                        RoundedRectangle(cornerRadius: 20, style: .continuous)
                            .stroke(Color.color_gray_border, lineWidth: 1)
                    )
                }.padding(10)
                HStack{
                    Image("menu").resizable().frame(width: 30, height: 30, alignment: .center).onTapGesture {
                        self.isListModel.toggle()
                    }
                    Spacer()
                    Text(self.orderbyStr).font(.subheadline).padding(0).onTapGesture {
                        isShowOrderBy=true
                    }.actionSheet(isPresented: self.$isShowOrderBy, content: {
                        ActionSheet(title: Text("选择排序方式"), message: nil, buttons: [.default(Text("按创建日期排序"),action:
                                                                                                            {self.orderbyStr="按创建日期排序"
                                                                                                                self.orderbyIndex=0
                                                                                                                sqliteViewModel.getNotes(keyWord: searchContent, orderby: orderbyIndex)
                                                                                                            }),.default(Text("按编辑日期排序"),action:
                                                                                                                            {self.orderbyStr="按编辑日期排序"
                                                                                                                                self.orderbyIndex=1
                                                                                                                                sqliteViewModel.getNotes(keyWord: searchContent, orderby: orderbyIndex)
                                                                                                                            }),.default(Text("按标题排序"),action:
                                                                                                                                            {self.orderbyStr="按标题排序"
                                                                                                                                                self.orderbyIndex=2
                                                                                                                                                sqliteViewModel.getNotes(keyWord: searchContent, orderby: orderbyIndex)
                                                                                                                                            }),.cancel(Text("取消"))])
                    })
                    Image("down").resizable().frame(width: 30, height: 30, alignment: .center)
                }.padding(.leading,10)
                .padding(.trailing,10)
                Divider().padding(5)
                if isListModel{
                    List{
                        ForEach(self.sqliteViewModel.noteList) { item in
                            listModelItemview(item: item,orderbyIndex: self.$orderbyIndex)
                        }.onDelete(perform: { offsets in
                            let index = offsets[offsets.startIndex]
                            print("删除项：\(index)")
                            if sqliteViewModel.delete(note: self.sqliteViewModel.noteList[index]) {
                                Toast(text: "删除成功").show()
                                self.sqliteViewModel.noteList.remove(atOffsets: offsets)
                            }else{
                                Toast(text: "删除失败").show()
                            }
                        })
                        
                    }.listStyle(PlainListStyle())
                }else{
                    ScrollView{
                        LazyVGrid(columns: gridItemLayout, spacing: 10,  content: {
                            //使用以下循环可以知道索引，但是在删除后会报数组越界，原因是找不到那个数据了，加上id可以使每一行重建
                            ForEach(self.sqliteViewModel.noteList.indices,id:\.self) { (index) in
                                
                                let item=self.sqliteViewModel.noteList[index]
                                VStack {
                                    if navigationLinkActive {
                                        NavigationLink("", destination: WriteNote(note:item), isActive: $navigationLinkActive)
                                    }
                                    gridModelItemview(item: item,orderbyIndex: self.$orderbyIndex).frame(width:self.width/3-10,height:100)
                                        .background(Color.white)
                                        .padding(0)
                                        .cornerRadius(10).overlay(
                                            RoundedRectangle(cornerRadius: 10, style: .continuous)
                                                .stroke(Color.color_gray_border, lineWidth: 1)
                                        )
                                }.actionSheet(isPresented: $isShowActionSheet, content: {
                                    ActionSheet(title: Text("请选择操作"), message: nil, buttons: [.default(Text("编辑"),action: {
                                        navigationLinkActive=true
                                    }),.default(Text("删除"), action:
                                                    {
                                                        
                                                        if sqliteViewModel.delete(note: self.sqliteViewModel.noteList[index]) {
                                                            Toast(text: "删除成功").show()
                                                            sqliteViewModel.noteList.remove(at: index)
                                                            
                                                        }else{
                                                            Toast(text: "删除失败").show()
                                                        }
                                                    }
                                    ),
                                    .cancel(Text("取消"))])
                                }).onTapGesture {
                                    self.isShowActionSheet=true
                                }
                            }
                        })
                    }
                }
                
                
                Spacer()
                ZStack(content: {
                    Text("\(self.sqliteViewModel.noteList.count)篇备忘录").font(.subheadline)
                    HStack{
                        Spacer()
                        NavigationLink(
                            destination: WriteNote(),
                            label: {
                                Text(Image("edit"))
                            })
                        
                    }
                }).padding()
            }.background(Color.white).navigationTitle("备忘录")
        }
    }
}

struct MainView_Previews: PreviewProvider {
    static var previews: some View {
        MainView()
    }
}

struct listModelItemview: View {
    var  item:NoteModel
    @Binding var orderbyIndex:Int
    
    var body: some View {
        NavigationLink(
            destination: WriteNote(note:item),
            label: {
                VStack{
                    HStack{
                        Text(item.title).lineLimit(1).truncationMode(.tail)
                        Spacer()
                    }
                    HStack{
                        (Text(orderbyIndex==1 ? "编辑于:\( Date.stampToString(stamp: item.updateTimeStamp))": "创建于:\(Date.stampToString(stamp: item.createTimeStamp))") + Text("    ") + Text(item.content)).fontWeight(.thin).font(.system(size: 10)).lineLimit(1).truncationMode(.tail)
                        Spacer()
                    }.padding(.top,5)
                }
            })
    }
}
struct gridModelItemview: View {
    var  item:NoteModel
    @Binding var orderbyIndex:Int
    
    
    var body: some View {
        
        VStack{
            
            HStack {
                Text(item.title).foregroundColor(.black).fontWeight(.heavy).font(.system(size: 15)).lineLimit(2).truncationMode(.tail)
                Spacer()
            }
            HStack {
                Text(item.content).foregroundColor(.black).fontWeight(.light).font(.system(size: 10)).lineLimit(2).truncationMode(.tail)
                Spacer()
            }
            HStack {
                Text(orderbyIndex==1 ? "\( Date.stampToString(stamp: item.updateTimeStamp))": "\(Date.stampToString(stamp: item.createTimeStamp))").foregroundColor(.black).fontWeight(.thin).font(.system(size: 10)).lineLimit(1).truncationMode(.tail)
                Spacer()
            }
            Spacer()
            
        }.padding(10)
    }
}
